<?php

namespace app\admin\model;

use think\Model;
use think\model\relation\BelongsTo;


class Coursepaper extends Model
{


    // 表名
    protected $name = 'course_paper';

    // 自动写入时间戳字段
    protected $autoWriteTimestamp = false;

    // 定义时间戳字段名
    protected $createTime = false;
    protected $updateTime = false;
    protected $deleteTime = false;

    // 追加属性
    protected $append = [
        'create_time_text',
        'update_time_text'
    ];


    public function course(): BelongsTo
    {
        return $this->belongsTo('app\admin\model\Course', 'course_id', 'id', [], 'LEFT')->setEagerlyType(0);
    }

    public function category(): BelongsTo
    {
        return $this->belongsTo('app\admin\model\Questioncategory', 'category_id', 'id', [], 'LEFT')->setEagerlyType(0);
    }


    public function getCreateTimeTextAttr($value, $data)
    {
        $value = $value ? $value : (isset($data['create_time']) ? $data['create_time'] : '');
        return is_numeric($value) ? date("Y-m-d H:i:s", $value) : $value;
    }


    public function getUpdateTimeTextAttr($value, $data)
    {
        $value = $value ? $value : (isset($data['update_time']) ? $data['update_time'] : '');
        return is_numeric($value) ? date("Y-m-d H:i:s", $value) : $value;
    }

    protected function setCreateTimeAttr($value)
    {
        return $value === '' ? null : ($value && !is_numeric($value) ? strtotime($value) : $value);
    }

    protected function setUpdateTimeAttr($value)
    {
        return $value === '' ? null : ($value && !is_numeric($value) ? strtotime($value) : $value);
    }

    public function setQuestionCount($id, $count)
    {
        // 更新试卷题目数量
        $this->where(['id' => $id])->update(['question_count' => $count]);
    }

    public function createByName($course_id, $category_id, $name)
    {
        // 判断是否存在,存在则返回试卷
        $paper = $this->where([
            'course_id' => $course_id,
            'category_id' => $category_id,
            'name' => $name
        ])->find();
        if ($paper) {
            return $paper->id;
        }
        // 不存在则创建新试卷
        $data = [
            'name' => $name,
            'course_id' => $course_id,
            'category_id' => $category_id,
            'create_time' => time(),
            'update_time' => time(),
            'is_free' => 0,
            'question_count' => 0
        ];

        return $this->insertGetId($data);
    }

}
